package com.ruoyi.controller;

import com.ruoyi.common.core.domain.R;

import com.ruoyi.common.entity.Category;
import com.ruoyi.common.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/category")
public class CategoryController {

    private final CategoryService categoryService;

    @Autowired
    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    /**
     * 获取所有启用的分类
     */
    @GetMapping("/list")
    public R<List<Category>> listActiveCategories() {
        List<Category> categories = categoryService.getAllActiveCategories();
        return R.ok(categories);
    }

    /**
     * 根据ID获取分类
     */
    @GetMapping("/{id}")
    public R<Category> getCategoryById(@PathVariable Integer id) {
        Category category = categoryService.getCategoryById(id);
        if (category != null) {
            return R.ok(category);
        } else {
            return R.fail("分类未找到");
        }
    }

    /**
     * 创建新分类
     */
    @PostMapping
    public R<Category> createCategory(@Valid @RequestBody Category category) {
        try {
            Category savedCategory = categoryService.saveCategory(category);
            return R.ok(savedCategory);
        } catch (Exception e) {
            return R.fail("创建分类失败: " + e.getMessage());
        }
    }

    /**
     * 更新分类
     */
    @PutMapping("/{id}")
    public R<Category> updateCategory(@PathVariable Integer id, @Valid @RequestBody Category category) {
        try {
            Category updatedCategory = categoryService.updateCategory(id, category);
            if (updatedCategory != null) {
                return R.ok(updatedCategory);
            } else {
                return R.fail("分类未找到，无法更新");
            }
        } catch (Exception e) {
            return R.fail("更新分类失败: " + e.getMessage());
        }
    }

    /**
     * 删除分类
     */
    @DeleteMapping("/{id}")
    public R<Void> deleteCategory(@PathVariable Integer id) {
        try {
            categoryService.deleteCategory(id);
            return R.ok(null);
        } catch (Exception e) {
            return R.fail("删除分类失败: " + e.getMessage());
        }
    }
}